/*
 * Copyright 2013-2019 Xia Jun(3979434@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************************************
 *                                                                                     *
 *                        Website : http://www.farsunset.com                           *
 *                                                                                     *
 ***************************************************************************************
 */
package com.master.demo.im.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.master.common.api.IPageInfo;
import com.master.common.api.Query;
import com.master.common.api.ResponseInfo;
import com.master.common.enums.StatusEnum;
import com.master.common.exception.ErrorException;
import com.master.common.utils.DateUtil;
import com.master.common.utils.DozerUtil;
import com.master.common.validator.ValidatorUtil;
import com.master.demo.im.component.redis.KeyValueRedisTemplate;
import com.master.demo.im.mapper.SessionMapper;
import com.master.demo.im.pojo.command.SessionCommand;
import com.master.demo.im.pojo.entity.Session;
import com.master.demo.im.pojo.vo.SessionVO;
import com.master.demo.im.service.ISessionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * 在线信息接口 实现类
 *
 * @author: Yang
 * @date: 2022/07/05
 * @version: 1.0.0
 * Copyright Ⓒ 2022 Master Computer Corporation Limited All rights reserved.
 */
@Service
public class SessionServiceImpl extends ServiceImpl<SessionMapper, Session> implements ISessionService {
    @Resource
    private SessionMapper sessionMapper;
    @Resource
    private KeyValueRedisTemplate keyValueRedisTemplate;

    /**
     * 根据id获取在线会话信息信息
     *
     * @param id 在线会话信息id
     * @return
     */
    private Session getSession(Long id) {
        Session session = sessionMapper.selectById(id);
        if (ValidatorUtil.isNull(session)) {
            throw new ErrorException("在线会话信息信息不存在，无法操作");
        }
        return session;
    }

    @Override
    public ResponseInfo<IPageInfo<SessionVO>> pageSession(Query query) {
        IPage<SessionVO> iPage = sessionMapper.pageSession(new Page<>(query.getCurrent(), query.getSize()), query);
        return ResponseInfo.success(new IPageInfo(iPage.getCurrent(), iPage.getSize(), iPage.getTotal(), iPage.getRecords()));
    }

    @Override
    public ResponseInfo<List<SessionVO>> listSession(Query query) {
        return ResponseInfo.success(sessionMapper.listSession(query));
    }

    @Override
    public ResponseInfo<SessionVO> getSessionById(Long id) {
        return ResponseInfo.success(DozerUtil.convertor(getSession(id), SessionVO.class));
    }

    @Override
    public ResponseInfo saveSession(SessionCommand command) {
        Session session = DozerUtil.convertor(command, Session.class);
        session.setBindTime(DateUtil.getTimestamp());
        session.setStatus(StatusEnum.ENABLED.getValue());
        try {
            session.setHost(InetAddress.getLocalHost().getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        sessionMapper.insert(session);
        return ResponseInfo.success();
    }

    @Override
    public ResponseInfo updateSession(SessionCommand command) {
        Session session = getSession(command.getId());
        DozerUtil.convertor(command, session);
        sessionMapper.updateById(session);
        return ResponseInfo.success();
    }

    @Override
    public ResponseInfo removeSessionByIds(List<Long> ids) {
        sessionMapper.deleteBatchIds(ids);
        return ResponseInfo.success();
    }

    @Override
    public ResponseInfo removeSessionById(Long id) {
        sessionMapper.deleteById(id);
        return ResponseInfo.success();
    }

    @Override
    public ResponseInfo updateStatus(String uid, String nid, Integer status) {
        sessionMapper.updateStatus(uid, nid, status);
        return ResponseInfo.success();
    }

    @Override
    public ResponseInfo openApns(String uid, String deviceToken) {
        keyValueRedisTemplate.openApns(uid, deviceToken);
        sessionMapper.openApns(uid, Session.CHANNEL_IOS);
        return ResponseInfo.success();
    }

    @Override
    public ResponseInfo closeApns(String uid) {
        keyValueRedisTemplate.closeApns(uid);
        sessionMapper.closeApns(uid, Session.CHANNEL_IOS);
        return ResponseInfo.success();
    }

}
